import React, { Component } from 'react'
import { Link, Outlet, useNavigate } from 'react-router-dom'

// v6使用useNavigate实现前进后退等操作, 需要封装hoc组件
function anonyCom(MessCom) {
	return (props) => {
		let navigate = useNavigate();
		return <MessCom {...props} navigate={navigate} />
	}
}

class Message extends Component {
	state = {
		messageArr_param: [
			{ id: '01', title: 'Message_param-01' },
			{ id: '02', title: 'Message_param-02' },
			{ id: '03', title: 'Message_param-03' },
		],
		messageArr_search: [
			{ id: '01', title: 'Message_search-01' },
			{ id: '02', title: 'Message_search-02' },
			{ id: '03', title: 'Message_search-03' },
		],
		messageArr_state: [
			{ id: '01', title: 'Message_state-01' },
			{ id: '02', title: 'Message_state-02' },
			{ id: '03', title: 'Message_state-03' },
		],
	}

	replaceShow = (msgObj) => {
		// param参数 replace跳转
		// 编写代码, 实现跳转到Detail组件, 且为replace跳转(无痕浏览)
		this.props.navigate(`details_param/${msgObj.id}/${msgObj.title}`, {
			replace: true,
		})
	}
	pushShow = (msgObj) => {
		// state参数 push跳转
		this.props.navigate('details_state', {
			state: {
				id: msgObj.id,
				title: msgObj.title
			}
		})
	}

	// navigate传递数字, 正数前进, 负数后退, 可以传包含replace和state的对象
	goBack = () => {
		this.props.navigate(-1);
	}

	goOne = () => {
		this.props.navigate(1);
	}

	goTwo = () => {
		this.props.navigate(2);
	}

	render() {
		const { messageArr_param, messageArr_search, messageArr_state } = this.state
		return (
			<div>
				<ul>
					{
						messageArr_param.map((msgObj) => {
							return (
								<li key={msgObj.id}>
									{/* params传递参数 /xxx/xxx */}
									<Link to={`details_param/${msgObj.id}/${msgObj.title}`}>{msgObj.title}</Link>
									&nbsp;<button onClick={() => (this.replaceShow(msgObj))}>replace查看</button>
								</li>
							);
						})
					}
					<hr />
					{
						messageArr_search.map((msgObj) => {
							return (
								<li key={msgObj.id}>
									{/* search传递参数 ?id=xxxtitle=xxx */}
									<Link to={`details_search/?id=${msgObj.id}&title=${msgObj.title}`}>{msgObj.title}</Link>
								</li>
							);
						})
					}
					<hr />
					{
						messageArr_state.map((msgObj) => {
							return (
								<li key={msgObj.id}>
									{/* state传递参数 */}
									<Link to='details_state' state={{ id: msgObj.id, title: msgObj.title }}>{msgObj.title}</Link>
									&nbsp;<button onClick={() => { this.pushShow(msgObj) }}>push查看</button>
								</li>
							);
						})
					}
				</ul>
				<hr />
				&nbsp;<button onClick={this.goBack}>回退</button>
				&nbsp;<button onClick={this.goOne}>前进</button>
				&nbsp;<button onClick={this.goTwo}>go 2</button>
				<hr />
				{/* 嵌套路由 */}
				<Outlet />
			</div>
		)
	}
}

export default anonyCom(Message);